import React from 'react';
import { withRouter } from 'react-router-dom';
import {Tools,Toast,Icon} from 'weaver-mobile';
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import DocConstant from "../../util";
import {GetUrlParam,SetTitle,getWpsSign} from '../../util/Utils'
const getLabel = Tools.getLabel;

@withRouter
@inject("attachStore","docStore")
@observer
class OpenAttach extends React.Component {
  componentDidMount() {
    const {location,attachStore,dataParams} = this.props;
    const {pathname} = location
    const paths = pathname.split("/");
    const fileid = paths[paths.length - 1];

    //判断是否有查看权限
    let url = this.props.location.search;
    let resource = GetUrlParam(url,'resource');
    let type = GetUrlParam(url,'type');
    let fid = GetUrlParam(url,'fid');
    attachStore.init({resource,type,fid,fileid},this);
    attachStore.imgInited = false;
    attachStore.otherMouldUrlParams = DocConstant.getLocationUrlParams(); 
    //附件打开
      //title 设置在手机端，附件的名称
      // attachid  要打开的文件的id
      // prevTitle 当前的标题
      // let attachid = dataParams && dataParams.attachid ? dataParams.attachid : '';
      let title = '';
      let prevTitle = '',clickResource = "";
      this.props.didmount && this.props.didmount();
      title = dataParams && dataParams.title ? dataParams.title : '';
      prevTitle = dataParams && dataParams.prevTitle ? dataParams.prevTitle : '';
      clickResource  = dataParams && dataParams.resource ? dataParams.resource : '';
    //================
    if(resource!=='em'){
      attachStore.isConvertFileEnd = false;
      attachStore.convertFile({fileid:fileid,resource:clickResource})
      SetTitle(title,prevTitle,this);
    }
  }
  componentWillUnmount(){
    const {dataParams,attachStore} = this.props;
    let title = '';
    title = dataParams && dataParams.title ? dataParams.title : '';
    if(attachStore.isUsePoi){
      let iframeclass = document.getElementsByClassName("wm-route-layout")[0];
      iframeclass.style.width="100%";
    }
    Toast.hide();
    if (title) {
      if (DocConstant.isApp()) {
        window.em.changeTitle({
          title: this.prevTitle
        });
      } else {
        window.document.title = this.prevTitle;
      }
      this.props.unmount && this.props.unmount();
    }
    // attachStore.
  }
  setiframeHeight = () =>{
    try{
      let iframeList = document.getElementsByTagName("iframe"),
      domNode = iframeList && iframeList[0].contentWindow.document,
      mainiframe = document.getElementById("mainiframe"),
      iframeclass = document.getElementsByClassName("wm-route-layout")[0],
      pagewidth = window.innerWidth,
      pageheight = window.innerHeight,
      domWidth = domNode.body.scrollWidth,
      domHight = domNode.body.scrollHeight,
      iframeBodyclass = domNode.getElementsByClassName("b2");
      let d1class = domNode.getElementsByClassName("d1");
        let d2class = domNode.getElementsByClassName("d2");
        if(d1class){
          for(let i = 0;i<d1class.length;i++){
            d1class[i].style.margin = "0";
            d1class[i].style.padding = "10px";
          }
        }
        if(d2class){
          for(let i = 0;i<d2class.length;i++){
            d2class[i].style.margin = "0";
            d2class[i].style.padding = "10px";
          }
        }
      for(let i = 0;i<iframeBodyclass.length;i++){
        iframeBodyclass[i].style.margin = "0";
        iframeBodyclass[i].style.padding = "10px";
      }
      if (!domNode) return;
      domHight = domHight<pageheight ? pageheight : domHight;
      domWidth = domWidth<pagewidth ?pagewidth : domWidth;
      mainiframe.style.height=domHight+"px";
      // iframeclass.style.width=domWidth+"px";
    } catch(e){
        // 防止跨域报错
    }
}

    setDocLock = () =>{
        try{
            const {attachStore,docStore} = this.props;
            let iframeList = document.getElementsByTagName("iframe");
		    	if(docStore.docisLock){
			     for(let index =0;index < iframeList.length; index++){
                let domNode = iframeList && iframeList[index].contentWindow.document;
                  if (!domNode) return;
                  if(domNode.body){
                   domNode.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
                   domNode.body.onselectstart = function () {return false};
                 }
				if(document.body){
			      document.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
			      document.body.onselectstart = function () {return false};
			    }
			  }
			}
         } catch(e){
        // 防止跨域报错
         }
    }
  
  initImg = () => {
    try {
      const {attachStore} = this.props;
      let iframeList = document.getElementsByTagName("iframe");
      /*if (iframeList.length > 0) {
        let doc = iframeList[0].contentWindow.document;
        doc.addEventListener("click", this.openLink);
      }*/
      let domNode = iframeList && iframeList[0].contentWindow.document;
      if (!domNode) return;
      let imgNodeList = Array.from(domNode.querySelectorAll("img"));
      imgNodeList.forEach((img, index) => {
        img.onload = (e) => {
          let {naturalWidth, naturalHeight} = e.target;
          attachStore.updateImg(index, {w: naturalWidth, h: naturalHeight})
        }
        img.onclick = (...args) => {
          attachStore.openImg(index);
        };
      });
      let imgList = imgNodeList.map((img) => (
        {
          url: img.src,
          w: img.naturalWidth,
          h: img.naturalHeight,
        }
      ));
      attachStore.setImgList(imgList);
    } catch(e) {
      // 防止跨域报错
    }
    setTimeout(()=>{
      this.setDocLock();
       },500
     );
  const {attachStore} = this.props;
  if(attachStore.isUsePoi){
    this.setiframeHeight();
  }
  
  }


  render() {
    const {attachStore} = this.props;
    const {
      // imgList = [],
      // imgInited,
      // imgVisible,
      // imgIndex,
      canReader,
      shareCancle,
      fileDel,
      isConvertFileSuccess,
      convertMessage,
      isConvertFileEnd
    } = attachStore;
    if(!canReader){
      if(shareCancle){
        return (
          <div className="wea-doc-whitebg">
            <div className="wea-doc-error">
              <Icon type="no-data" size="lg" />
              <div>{getLabel(516293, "分享已被取消")}</div>
            </div>
          </div>
        );
      }
      if(fileDel){
        return (
          <div className="wea-doc-whitebg">
            <div className="wea-doc-error">
              <Icon type="no-data" size="sm" />
              <div>{getLabel(516294, "文件已被删除")}</div>
            </div>
          </div>
        );
      }
    }
    let iframeParam = {};
    iframeParam = attachStore.isUsePoi?{scrolling:"no"}:{};
    return (
        <div className="wm-route-layout" >
            {
              isConvertFileEnd
              ? isConvertFileSuccess
                ? <div className="wea-doc-openattach"> 
                  <iframe 
                    key="iframe"
                    id="mainiframe"
                    src={attachStore.openAttachPath} 
                    title={getLabel(388748, "查看文件")} 
                    frameBorder="0" 
                    iframeParam
                    style={{height: '100%', width: '100%'}}
                    onLoad={()=>{
                    	this.initImg();
                    	getWpsSign("mainiframe");
                    }}
                    >
                  </iframe>
                  </div>
                : <div className="wea-doc-error">
                    <Icon type="cross" size="lg"/>
                    <div>{convertMessage?convertMessage:getLabel(516295,"无法打开")}</div>
                  </div>  
              : ''
            }
            {
            // imgInited && PhotoSwipe.showImage(imgList,imgIndex)
              //  <PhotoSwipe
              //   options={{
              //     shareEl: false
              //   }}
              //   items={imgList}
              //   visible={imgVisible}
              //   index={imgIndex}
              //   onClose={attachStore.closeImg}
              // />
            } 
        </div>
    );
  }
}
export default OpenAttach